<template>
    <el-upload drag :on-change="onUpload" :auto-upload="false" ref="uploadfile" :show-file-list="false">文件上传</el-upload>

    <div style="width: 200px; margin-top: 10px;"><el-progress :text-inside="true" :stroke-width="26"
            :percentage="percentage" v-show="percentage" /></div>
</template>

<script setup lang="ts">
import { getFileMd5 } from '../../utils/md5'
import { computed, reactive } from 'vue'
import { bigFilePush, com } from '@/api/Admin/AdminApi'
let percentage = ref(0)


const onUpload = async (File: any) => {
    percentage.value = 0
    const chunkSize = 10 * 1024; // 分片大小
    const file = File.raw // 文件
    const fileSize = File.size // 文件大小
    let chunkCount = Math.ceil(fileSize / chunkSize) // 分片数量
    if (chunkSize > fileSize) { // 文件过小就一片
        chunkCount = 1
    }
    // 文件md5，给文件一个唯一标识
    const fileMd5 = await getFileMd5(file, chunkCount, chunkSize);
    // 向 Worker 发送消息
    // 上传分片
    for (let i = 0; i < chunkCount; i++) {
        const start = i * chunkSize //分片开始
        const end = Math.min(fileSize, start + chunkSize) // 分片结束
        const _chunkFile = File.raw.slice(start, end) // 分片文件
        // 定义分片上传接口参数，跟后端商定
        const formdata: any = new FormData()
        formdata.append('chunk', _chunkFile)


        // 检查分片文件是否上传-没有上传则上传
        // const { data } = await com({ md5: fileMd5 }) // 检验接口-自己定义
        // console.log(fileMd5)
        // if (1) {
        // console.log("开始上传第" + i + "个分片")
        let { data } = await bigFilePush({
            index: i,
            chunkSize: _chunkFile.size,
            fileName: File.name,
            md5: fileMd5,
            chunkTotal: chunkCount,
            fileSize: fileSize
        }, formdata) // 上传接口-自己定义
        if (data.code == 201) {
            percentage.value = Math.floor(((i + 1) / chunkCount) * 100)
            if (percentage.value == 100) {
                ElMessage({
                    message: '上传成功',
                    type: 'success',
                })
            }
        }
        // }
    }

    // 合并
    const mergeData = { // 合并参数
        //     fileName: File.name, 
        //     fileSign: fileMd5,
        //     ...
        //  }
        // mergeFile(mergeData)// 合并接口-自己定义
    }
}
</script>

<style lang="less" scoped>
.demo-progress .el-progress--line {
    margin-bottom: 15px;
    width: 350px;
}
</style>
<style></style>